package com.mobisystems.youpark.settings;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import com.beardedhen.androidbootstrap.BootstrapButton;
import com.mobisystems.youpark.R;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseUser;
import com.parse.SaveCallback;

import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CarInformationActivity extends Activity {
	private Dialog updateVehicleDialog;
	private BootstrapButton btnCancel, btnSave;
	private TextView tvCarInfo;
	private EditText etMake, etModel, etColor;
	private String color, make, model;

	// camera constants
	private static final String BITMAP_STORAGE_KEY = "viewbitmap";
	private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
	private ImageView mImageView;
	private Bitmap mImageBitmap;
	private String mCurrentPhotoPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_car_information);

		// using custom action bar
		ActionBar customActionBar = getActionBar();
		customActionBar.setDisplayShowHomeEnabled(false);
		customActionBar.setDisplayShowTitleEnabled(false);
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.custom_actionbar, null);
		TextView titleTextView = (TextView) view.findViewById(R.id.title_text);
		titleTextView.setText("Vehicle Information");
		view.findViewById(R.id.button_settings).setVisibility(View.INVISIBLE);
		view.findViewById(R.id.button_switch_modes).setVisibility(View.GONE);
		ImageButton backButton = (ImageButton) view.findViewById(R.id.button_back);
		backButton.setVisibility(View.VISIBLE);
		backButton.setBackgroundResource(R.drawable.back_button);
		backButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				onBackPressed();
			}
		});
		customActionBar.setCustomView(view);
		customActionBar.setDisplayShowCustomEnabled(true);
		
		

		mImageView = (ImageView) findViewById(R.id.carImage);
		mImageBitmap = null;

		Button picBtn = (Button) findViewById(R.id.cameraButton);
		setBtnListenerOrDisable(picBtn, mTakePicOnClickListener, MediaStore.ACTION_IMAGE_CAPTURE);

		updateVehicleDialog = new Dialog(CarInformationActivity.this);
		updateVehicleDialog.setContentView(R.layout.dialog_update_car);

		btnCancel = (BootstrapButton) updateVehicleDialog.findViewById(R.id.btnCancel);
		btnSave = (BootstrapButton) updateVehicleDialog.findViewById(R.id.btnSave);
		etMake = (EditText) updateVehicleDialog.findViewById(R.id.etMake);
		etModel = (EditText) updateVehicleDialog.findViewById(R.id.etModel);
		etColor = (EditText) updateVehicleDialog.findViewById(R.id.etColor);
		tvCarInfo = (TextView) findViewById(R.id.tvCarInfo);

		color = "update";
		make = "vehicle";
		model = "information";
		tvCarInfo.setText(color + " " + make + " " + model);

		// set information for current user
		final ParseUser currentUser = ParseUser.getCurrentUser();
		if (currentUser != null) {
			// set vehicle information
			if (TextUtils.isEmpty((String) currentUser.get("vehicleColor"))) {
				Log.w("myLog", "No car information is set");
				tvCarInfo.getText().toString();
				updateVehicleDialog.setTitle("Add Vehicle Info");
				updateVehicleDialog.show();
			} else {
				color = (String) currentUser.get("vehicleColor");
				make = (String) currentUser.get("vehicleMake");
				model = (String) currentUser.get("vehicleModel");
				tvCarInfo.setText(color + " " + make + " " + model);
			}
			// set vehicle picture
			if (currentUser.get("vehiclePic") == null) {
				Log.w("myLog", "No Picture Stored on server");
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("No vehicle photo was found. Please update your vehicle photo.")
						.setNegativeButton("Cancel", null)
						.setPositiveButton("Take a new Photo", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dispatchTakePictureIntent();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				// setPic(R.drawable.blank_car);
				Drawable d = getResources().getDrawable(R.drawable.blank_car);
				Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
				byte[] bitmapdata = stream.toByteArray();
				setPic(bitmapdata);
			} else {
				Log.w("myLog", "Picture exists, converting to jpg");
				try {
					ParseFile pFile = (ParseFile) currentUser.get("vehiclePic");
					byte[] file = pFile.getData();
					setPic(file);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		} else {
			Log.w("myLog", "ParseUser content Null");
		}

		btnCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(tvCarInfo.getText().toString()))
					Toast.makeText(CarInformationActivity.this, "All fields must be completed", Toast.LENGTH_LONG)
							.show();
				else
					updateVehicleDialog.dismiss();
			}
		});

		btnSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// reset errors
				etMake.setError(null);
				etModel.setError(null);
				etColor.setError(null);
				boolean error = false;

				make = etMake.getText().toString();
				model = etModel.getText().toString();
				color = etColor.getText().toString();

				// check for empty fields
				if (TextUtils.isEmpty(color)) {
					etColor.setError("Color cannot be empty");
					etColor.requestFocus();
					error = true;
				}
				if (TextUtils.isEmpty(model)) {
					etModel.setError("Model cannot be empty");
					etModel.requestFocus();
					error = true;
				}
				if (TextUtils.isEmpty(make)) {
					etMake.setError("Make cannot be empty");
					etMake.requestFocus();
					error = true;
				}

				if (!error) {

					tvCarInfo.setText(color + " " + make + " " + model);
					updateVehicleDialog.dismiss();
					try {
						currentUser.put("vehicleColor", color);
						currentUser.put("vehicleMake", make);
						currentUser.put("vehicleModel", model);
						currentUser.saveInBackground();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	public void updateInfo(View v) {
		tvCarInfo.getText().toString();
		updateVehicleDialog.setTitle("Update Vehicle Info");
		etMake.setText(make);
		etModel.setText(model);
		etColor.setText(color);
		updateVehicleDialog.show();

	}

	// camera and photo handling functions
	Button.OnClickListener mTakePicOnClickListener = new Button.OnClickListener() {
		@Override
		public void onClick(View v) {
			dispatchTakePictureIntent();
		}
	};

	private void setBtnListenerOrDisable(Button btn, Button.OnClickListener onClickListener, String intentName) {
		if (isIntentAvailable(this, intentName)) {
			btn.setOnClickListener(onClickListener);
		} else {
			btn.setText("Cannot " + btn.getText());
			btn.setClickable(false);
		}
	}

	/**
	 * Indicates whether the specified action can be used as an intent. This
	 * method queries the package manager for installed packages that can
	 * respond to an intent with the specified action. If no suitable package is
	 * found, this method returns false.
	 * 
	 * @return True if an Intent with the specified action can be sent and
	 *         responded to, false otherwise.
	 */
	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private void dispatchTakePictureIntent() {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File f = null;

		try {
			f = setUpPhotoFile();
			mCurrentPhotoPath = f.getAbsolutePath();
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		} catch (IOException e) {
			e.printStackTrace();
			f = null;
			mCurrentPhotoPath = null;
		}

		startActivityForResult(takePictureIntent, 0);
	}

	private File setUpPhotoFile() throws IOException {
		File albumF = getAlbumDir();
		File imageF = new File(albumF.getAbsolutePath(), "vehicleImage.jpg");
		Log.w("myLog", imageF.getAbsolutePath());
		mCurrentPhotoPath = imageF.getAbsolutePath();
		return imageF;
	}

	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

			storageDir = getExternalFilesDir(null);
			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (mCurrentPhotoPath != null) {
				// setPic();// set picture in imageview
				Log.w("myLog", mCurrentPhotoPath);

				/* Decode the JPEG file into a Bitmap */
				Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, null);
				
				int height = bitmap.getHeight();
				int width = bitmap.getWidth();
				float bitmapRatio = (float)width / (float) height;
		        if (bitmapRatio > 0) {
		            width = 1000;
		            height = (int) (width / bitmapRatio);
		        } else {
		            height = 1000;
		            width = (int) (height * bitmapRatio);
		        }
		        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
				
				/* Rotate the bitmap, if necessary. Fixes some issues on some android devices */
				ExifInterface ei = null;
				try {
					ei = new ExifInterface(mCurrentPhotoPath);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
				switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					bitmap = RotateBitmap(bitmap, 90);
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					bitmap = RotateBitmap(bitmap, 180);
					break;
				}
				
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
		        
				bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream);
				byte[] photoData = stream.toByteArray();
				setPic(photoData);

				ParseFile file = new ParseFile("carPic.jpg", photoData);
				// file.saveInBackground();
				final ParseUser currentUser = ParseUser.getCurrentUser();
				currentUser.put("vehiclePic", file);

				file.saveInBackground(new SaveCallback() {

					public void done(ParseException e) {
						if (e != null) {
							Toast.makeText(CarInformationActivity.this, "Error saving: " + e.getMessage(),
									Toast.LENGTH_LONG).show();
						} else {
							currentUser.saveInBackground();
						}
					}
				});

				mCurrentPhotoPath = null;
			}
		}
	}

	// displays pic in app
	private void setPic(byte[] file) {

		/* There isn't enough memory to open up more than a couple camera photos */
		/* So pre-scale the target bitmap into which the file is decoded */

		/* Get the size of the ImageView */
		int targetW = mImageView.getWidth();
		int targetH = mImageView.getHeight();

		/* Get the size of the image */
		BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		//BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
		BitmapFactory.decodeByteArray(file, 0, file.length, bmOptions);
		int photoW = bmOptions.outWidth;
		int photoH = bmOptions.outHeight;

		/* Figure out which way needs to be reduced less */
		int scaleFactor = 1;
		if ((targetW > 0) || (targetH > 0)) {
			scaleFactor = Math.min(photoW / targetW, photoH / targetH);
		}

		/* Set bitmap options to scale the image decode target */
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		/* Decode the JPEG file into a Bitmap */
		Bitmap bitmap = BitmapFactory.decodeByteArray(file, 0, file.length, bmOptions);

		// assign to handle screen rotation issue
		mImageBitmap = bitmap;

		/* Associate the Bitmap to the ImageView */
		mImageView.setImageBitmap(bitmap);
		mImageView.setVisibility(View.VISIBLE);
	}

	public static Bitmap RotateBitmap(Bitmap source, float angle) {
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
	}

	// Some lifecycle callbacks so that the image can survive orientation change
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
		outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null));

		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
		mImageView.setImageBitmap(mImageBitmap);
		mImageView.setVisibility(savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ? ImageView.VISIBLE
				: ImageView.INVISIBLE);

	}
}
